﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaixin.Components.Tycoon.DAL;
using Kaixin.Components.Tycoon.DTO;

namespace Kaixin.Components.Tycoon.BLL
{
    /// <summary>
    /// 委托交易
    /// 创建：2009-12-10
    /// 版本：1.0
    /// 作者：吴鸣震
    /// </summary>
    class Commission
    {
        #region field
        private static Persistence<Orders> _dal = new OrdersDAL();
        #endregion

        #region private

        private static List<Orders> GetOrdersByGoods(Goods goods)
        {
            return _dal.GetAllItem().Where(o => o.GoodsID == goods.ID).ToList();
        }

        #endregion


        /// <summary>
        /// 委托交易
        /// </summary>
        /// <param name="goods">价格浮动商品</param>
        public static void Action(Goods goods)
        {
            List<IGrouping<string, Orders>> list = GetOrdersByGoods(goods).GroupBy(o => o.Email).ToList();
            foreach (var item in list)
            {
                List<Orders> orders = item.ToList();
                MyTycoon ty = new MyTycoon(orders[0].Email, orders[0].Password);
                foreach (var order in orders)
                {
                    if (order.IsSell && goods.CurrentPrice >= order.Price)
                    {
                        Goods myGoods = ty.GetMyGoods().Where(g => g.ID == goods.ID).FirstOrDefault();
                        if (myGoods != null)
                        {
                            ty.Sell(myGoods);
                        }
                    }
                    else if (goods.CurrentPrice <= order.Price && !order.IsSell)
                    {
                        ty.Buy(goods);
                    }
                }
            }
        }

    }
}
